﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Whoever.Framework.FileFormatConverter;


namespace Whoever.Website.Site.Services.Utilities
{
    public partial class PDFConverter : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadControls();
        }

        protected void LoadControls()
        {
            if (Master != null)
            {
                var homeButton = ((ServicesMaster)Master).GetControl("Utilities");
                homeButton.Style.Add("background-image", "url('/Resources/Image/Site/Button/ServiceButtonOn.png')");
            }
        }

        protected void btnConvert_Click(object sender, EventArgs e)
        {
            try
            {
                CleanMensajes();
                string UploadPath = Convert.ToString(Server.MapPath("/" + "ArchivosAConvertir/"));
                string UploadPathOutput = UploadPath + "\\Procesados" + "\\";
                if (FileUploadDocument.HasFile)
                {
                    if (!Directory.Exists(UploadPath))
                    {
                        Directory.CreateDirectory(UploadPath);
                        Directory.CreateDirectory(UploadPathOutput);                        
                        Whoever.Framework.IO.DirectoryExtension.ShareFolder(Path.GetDirectoryName(UploadPath), "FileConverted", string.Empty);
                    }
                    FileUploadDocument.SaveAs(UploadPath + FileUploadDocument.FileName);
                    WordConverter wdc = new WordConverter();
                    wdc.ChangeFormat(UploadPath + FileUploadDocument.FileName, UploadPathOutput, WordTypesConvert.PDF);
                    FileInfo flOutput = new FileInfo(wdc.LastFileConverter);
                    string outputUrl = "~/ArchivosAConvertir/Procesados/" + flOutput.Name;

                    lblError.Text = outputUrl;
                    Response.Redirect(outputUrl);
                }
                else
                {
                    //TODO: Poner una ventana piola o control piola.
                    lblError.Text = "No se ha seleccionado ningún archivo";
                }
            }
            catch (Exception ex)
            {
                lblError.Text = "Error al convertir el archivo. " + ex.Message; 
            }
        }

        protected void CleanMensajes()
        {
            lblError.Text = "";
        }               
    }            
}